package com.zyk.leetcode;

import java.util.Arrays;

/**
 * @author zhangsan
 * @date 2021/4/13 22:09
 */
public class A_HeapSort {

    public static void heapSort(int[] arr) {
        int heapSize = 0;
        for (int i = 0; i < arr.length; i++) {
            heapInsert(arr, i);
            heapSize++;
        }
        for (int i = 1; i < arr.length; i++) {
            swap(arr, 0, --heapSize);
            heapify(arr, 0, heapSize);
        }
    }

    public static void heapify(int[] arr, int index, int heapSize) {
        /*int L = index << 1 | 1;
        while (L <= heapSize) {
            int largest = L + 1 <= heapSize && arr[L + 1] < arr[L] ? L + 1 : L;
            if (arr[largest] < arr[index]) {
                swap(arr, largest, index);
                index = largest;
                L = index << 1 | 1;
            } else {
                break;
            }
        }*/
        int left = (index << 1) + 1;
        while (left < heapSize) {
            int largest = left + 1 < heapSize && arr[left + 1] > arr[left] ? left + 1 : left;
            largest = arr[largest] > arr[index] ? largest : index;
            if (largest == index) {
                break;
            }
            swap(arr, largest, index);
            index = largest;
            left = (largest<<1) + 1;
        }
    }

    public static void heapInsert(int[] arr, int index) {
        while (arr[index] > arr[((index - 1) / 2)]) {
            swap(arr, index, ((index - 1) >> 1));
            index = ((index - 1) >> 1);
        }
        /*// 第几个值, heapIndex第几个值
        int pi = (index - 1) >> 1;
        while (pi >= 0 && arr[index] < arr[pi]) {
            swap(arr, index, pi);
            heapIndex = pi;
            pi = (index - 1) >> 1;
        }*/
    }

    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }


    public static void main(String[] args) {
        int[] arr = {2, 5, 6, 3, 5, 8, 7, 4, 1, 2, 5};
        heapSort(arr);
        System.out.println(Arrays.toString(arr));
    }

}
